import hmac
import json
import base64
import datetime
from hashlib import sha256
from collections import OrderedDict
import urllib
import pymysql
import requests



class QingApi:
    def __init__(self):
        self.access_key_id = 'NVZXMHPSPKAKKYOTADQZ'
        self.secret_access_key = '38SBm8EVk6N138NG9sriqp7h2VOEqXpuKnx5Dyag'
        self.time_stamp = datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")
        self.url = "http://api.qingcloud.com/iaas/"
        self.url_path = '/iaas/'
        self.methods = 'GET'
        self.zone = 'pek3a'

    def getqingyunsignature(self, urlstr, secret_access_key):
        # 前面生成的被签名串

        string_to_sign = 'GET\n/iaas/\n'

        string_to_sign = string_to_sign + urlstr
        # print '最后的url参数：',string_to_sign
        # 先sha256编码
        h = hmac.new(secret_access_key, digestmod=sha256)
        h.update(string_to_sign.encode())
        # 再base64编码，去除空格
        sign = base64.b64encode(h.digest()).strip()
        # 再URL编码
        signature = urllib.parse.quote_plus(sign)

        return signature

    # 签名前排序
    def setdictsort(self, adict, types):
        i = 0
        if types == 'key':
            i = 0
        else:
            i = 1
        return sorted(adict.items(), key=lambda item: item[i])

    def postResust(self, iassurl):
        req = urllib.request.Request(iassurl)
        result = urllib.request.urlopen(req)
        response = json.loads(result.read().decode())
        print(response)

    # 根据参数返回接口结果
    def getqingyunapi(self, dictinfo):
        strinfo = x.setdictsort(dictinfo, 'key')
        # print '排序后：',strinfo
        # print(strinfo)
        urlstr = urllib.parse.urlencode(strinfo)
        # print 'url转化2：',urlstr
        # print(urlstr)
        signature = x.getqingyunsignature(urlstr, secret_access_key)
        print(signature)
        # h = hmac.new(secret_access_key.encode(), digestmod=sha256)
        # h.update(urlstr.encode())
        # sign = base64.b64encode(h.digest()).strip()
        # signature = urllib.parse.quote_plus(sign)
        # strsql = "http://api.qingcloud.com/iaas/?" + urlstr + "&signature=" + signature
        # print (strsql)
        strsql = "http://api.qingcloud.com/iaas/?" + urlstr + "&signature=" + signature
        # 调用青云接口获取对应的值
        retapistr = requests.get(strsql).content
        # print("retapistr值为:",retapistr,type(retapistr))
        print(retapistr)
        apijson = json.loads(retapistr)
        print(apijson)
        # print "apijson返回值:",apijson,type(apijson),apijson['total_count']
        return apijson


    def ecs_Check(self,resource):
        # od = OrderedDict()
        # od['access_key_id'] = self.access_key_id
        # od['action'] = "GetMonitor"
        # od['resource'] = resource
        # od['meters.1'] = "cpu"
        # od['meters.2'] = "memory"
        # od['meters.3'] = "disk-us-os"
        # od['start_time'] = "2022-12-04T09:00:22Z"  # 时间目前写死了
        # od['end_time'] = "2022-12-04T09:05:22Z"
        # od['signature_method'] = "HmacSHA256"
        # od['time_stamp'] = self.time_stamp
        # od['step'] = '5m'
        # od['signature_version'] = 1
        # od['zone'] = self.zone
        # self.time_stamp
        action = "GetMonitor"
        signature_method="HmacSHA256"
        dictinfo = {
            "action": action,
            "access_key_id": access_key_id,
            "resource": resource,
            "meters.1": "cpu",
            "meters.2": "memory",
            "meters.3": "disk-us-os",
            "start_time": "2022-12-04T09:00:22Z",
            "end_time": "2022-12-04T09:05:22Z",
            "signature_method": signature_method,
            "time_stamp": time_stamp,
            "step": '5m',
            "signature_version": 1,
            "zone": zone
        }
        apijson = x.getqingyunapi(dictinfo)
        print(apijson)
        # s_str = str(apijson['meters.1'])
        # return s_str

    def ecs_Info(self):
        od = OrderedDict()
        od['access_key_id'] = self.access_key_id
        od['action'] = "DescribeInstances"
        od['signature_method'] = "HmacSHA256"
        # od['image_id.1'] = "img-vbp7ftes"
        od['signature_version'] = 1
        od['time_stamp'] = self.time_stamp
        od['version'] = 1
        od['zone'] = self.zone
        od['status.1'] = "running"
        od['status.2'] = "stopped"
        od['limit'] = "10"
        od['offset'] = "0"

        od = self.sort_value(od)
        # print(od)
        data = urllib.parse.urlencode(od)

        # print(data)
        string_to_sign = self.methods + "\n" + self.url_path + "\n" + data
        h = hmac.new(self.secret_access_key, digestmod=sha256)
        h.update(string_to_sign.encode())
        sign = base64.b64encode(h.digest()).strip()
        signature = urllib.parse.quote_plus(sign)
        # print("signature是:"+signature)
        iaasUrl = self.url + "?" + data + "&signature=" + signature
        # print(iaasUrl)
        ckk = self.postResust(iaasUrl)
        ckk_status = ckk['action']
        str_ckk = str(ckk_status)
        return str_ckk



    def ecs_Price(self,resource):
        od = OrderedDict()
        od['access_key_id'] = self.access_key_id
        od['action'] = "GetChargeSums"
        od['signature_method'] = "HmacSHA256"
        # od['image_id.1'] = "img-vbp7ftes"
        od['signature_version'] = 1
        od['time_stamp'] = self.time_stamp
        od['version'] = 1
        od['zone'] = self.zone
        od['resource'] = resource
        od['duration'] = "weekly"
        od['limit'] = "2"

        od = self.sort_value(od)
        # print(od)
        data = urllib.parse.urlencode(od)
        # print(data)
        string_to_sign = self.methods + "\n" + self.url_path + "\n" + data
        h = hmac.new(self.secret_access_key.encode(), digestmod=sha256)
        h.update(string_to_sign.encode())
        sign = base64.b64encode(h.digest()).strip()
        signature = urllib.parse.quote_plus(sign)
        # print("signature是:"+signature)
        iaasUrl = self.url + "?" + data + "&signature=" + signature
        # print(iaasUrl)
        self.postResust(iaasUrl)
    def sort_value(self, old_dict):
        items = sorted(old_dict.items())
        new_dict = OrderedDict()
        for item in items:
            new_dict[item[0]] = old_dict[item[0]]
        return new_dict

if __name__ == '__main__':

    resource = 'i-vgfe6tl5'
    access_key_id = 'NVZXMHPSPKAKKYOTADQZ'
    secret_access_key = '38SBm8EVk6N138NG9sriqp7h2VOEqXpuKnx5Dyag'
    time_stamp = datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")
    zone = 'pek3a'
    x = QingApi()
    x.ecs_Check(resource)

    # x.ecs_Info()
    # x.ecs_Price(resource)
